package com.link.play.fit.ai.ui.main.adapter

import android.annotation.SuppressLint
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.view.isVisible
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.google.gson.Gson
import com.link.play.fit.ai.R
import com.link.play.fit.ai.bean.InfoIngredientsBean
import com.link.play.fit.ai.bean.RecentlyEatenData
import com.link.play.fit.ai.ext.d
import com.link.play.fit.ai.ui.view.AutoSwitchTextView
import com.link.play.fit.ai.ui.view.LoadLinearView
import com.link.play.fit.ai.ui.view.ProgressTextView
import com.link.play.fit.ai.ui.view.RotateImageView
import com.link.play.fit.ai.utils.DateEx.getPmDate
import com.link.play.fit.ai.utils.GradeUtils.getGradeByIntensity
import kotlin.math.roundToInt

class HomeRecentlyListAdapter(
    private val data: MutableList<RecentlyEatenData> = mutableListOf(),
    private val context: Context,
    private val onClick: (Int, Int, View) -> Unit
) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    companion object {
        private const val VIEW_TYPE_EXERCISE = 1
        private const val VIEW_TYPE_SCAN = 2
        private const val VIEW_TYPE_BUTTER = 3
    }
    private var texts:List<String> = listOf()
    init {
        texts = listOf(context.getString(R.string.Analyzing_food),
            context.getString(R.string.Separating_ingredients),
            context.getString(R.string.Breaking_down_macros),
            context.getString(R.string.Searching_nutrition_database),
            context.getString(R.string.Finalizing_results),
        )
    }


    // 根据状态返回不同ViewType
    override fun getItemViewType(position: Int): Int {
        return when (data[position].type) {
            1 -> VIEW_TYPE_EXERCISE
            2 -> VIEW_TYPE_SCAN
            3 -> VIEW_TYPE_BUTTER
            4 -> VIEW_TYPE_BUTTER
            else -> VIEW_TYPE_EXERCISE
        }
    }

    override fun getItemCount(): Int {
        return data.size
    }


    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        return when (viewType) {
            VIEW_TYPE_EXERCISE -> RunViewHolder(
                LayoutInflater.from(parent.context)
                    .inflate(R.layout.recently_run_item, parent, false)
            )

            VIEW_TYPE_SCAN -> FoodViewHolder(
                LayoutInflater.from(parent.context)
                    .inflate(R.layout.recently_food_item, parent, false)
            )

            VIEW_TYPE_BUTTER -> FoodNameViewHolder(
                LayoutInflater.from(parent.context)
                    .inflate(R.layout.recently_edit_item, parent, false)
            )

//            VIEW_TYPE_FOOD -> FoodViewHolder(
//                LayoutInflater.from(parent.context)
//                    .inflate(R.layout.recently_food_item, parent, false)
//            )
//
//            VIEW_TYPE_EDIT -> EditViewHolder(
//                LayoutInflater.from(parent.context)
//                    .inflate(R.layout.recently_edit_item, parent, false)
//            )

            else -> throw IllegalArgumentException("Invalid view type")
        }
    }

    // 绑定数据或设置事件
    @SuppressLint("SetTextI18n")
    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        when (holder) {
            is RunViewHolder -> {
                val dataLayout = holder.itemView.findViewById<ConstraintLayout>(R.id.dataLayout)
                val noneLayout = holder.itemView.findViewById<ConstraintLayout>(R.id.noneLayout)

                val timeText = holder.itemView.findViewById<TextView>(R.id.timeText)
                val calorieValueText = holder.itemView.findViewById<TextView>(R.id.calorieValueText)
                val intensityText = holder.itemView.findViewById<TextView>(R.id.intensityText)
                val pmText = holder.itemView.findViewById<TextView>(R.id.pmText)
                val runImg = holder.itemView.findViewById<ImageView>(R.id.runImg)
                val runText = holder.itemView.findViewById<TextView>(R.id.runText)
                val contentLayout =
                    holder.itemView.findViewById<ConstraintLayout>(R.id.contentLayout)
                val timeImg = holder.itemView.findViewById<ImageView>(R.id.timeImg)


                when (data[position].typeChild) {
                    0 -> { //run
                        runImg.setImageResource(R.mipmap.recently_icon_xie)
                        runText.text = context.getString(R.string.run)
                    }

                    1 -> { //weight life

                        runImg.setImageResource(R.mipmap.recently_icon_duanlian)
                        runText.text = context.getString(R.string.weight_lifting)
                    }

                    3 -> { //des
                        runImg.setImageResource(R.mipmap.recently_icon_duanlian)
                        runText.text = data[position].name.ifEmpty { data[position].describe }

                    }
                }
                when (data[position].showType) {
                    1 -> {
                        dataLayout.isVisible = true
                        noneLayout.isVisible = false
                    }

                    2 -> { //加载中
                        dataLayout.isVisible = false
                        noneLayout.isVisible = true
                    }
                }

                if (data[position].time > 0) {
                    timeText.isVisible = true
                    timeImg.isVisible = true
                    timeText.text = "${data[position].time} min"
                } else {
                    timeText.isVisible = false
                    timeImg.isVisible = false
                }

                pmText.text = getPmDate(data[position].createTime)
                calorieValueText.text = buildString {
                    append(data[position].caloriesDaily)
                    append(" ")
                    append(context.getString(R.string.calories))
                }
                intensityText.text = buildString {
                    append(context.getString(R.string.intensity))
                    append(" ")
                    append(getGradeByIntensity(data[position].intensityPercent))
                }

                contentLayout.setOnClickListener {
                    val currentPosition = holder.adapterPosition
                    if (currentPosition != RecyclerView.NO_POSITION) {
                        onClick.invoke(0, currentPosition, it)
                    }
                }
            }

            is FoodNameViewHolder -> { //自定义食物
                val dataLayout = holder.itemView.findViewById<ConstraintLayout>(R.id.dataLayout)
                val noneLayout = holder.itemView.findViewById<ConstraintLayout>(R.id.noneLayout)
                val failLayout = holder.itemView.findViewById<ConstraintLayout>(R.id.failLayout)
                val nameText = holder.itemView.findViewById<TextView>(R.id.nameText)
                val pmText = holder.itemView.findViewById<TextView>(R.id.pmText)
                val calorieValueText = holder.itemView.findViewById<TextView>(R.id.calorieValueText)
                val proteinText = holder.itemView.findViewById<TextView>(R.id.proteinText)
                val carbsText = holder.itemView.findViewById<TextView>(R.id.carbsText)
                val fatsText = holder.itemView.findViewById<TextView>(R.id.fatsText)
                val tapToText = holder.itemView.findViewById<TextView>(R.id.tapToText)
                val xImg = holder.itemView.findViewById<ImageView>(R.id.xImg)
                val contentLayout =
                    holder.itemView.findViewById<ConstraintLayout>(R.id.contentLayout)

                val finalText = holder.itemView.findViewById<AutoSwitchTextView>(R.id.finalText)
                val emptyView1 = holder.itemView.findViewById<LoadLinearView>(R.id.emptyView1)
                val emptyView2 = holder.itemView.findViewById<LoadLinearView>(R.id.emptyView2)
                val emptyView3 = holder.itemView.findViewById<LoadLinearView>(R.id.emptyView3)
                val emptyView4 = holder.itemView.findViewById<LoadLinearView>(R.id.emptyView4)

                finalText.apply {
                    setTextList(texts)
                    startSwitching()
                }

                nameText.text = data[position].foodName
                pmText.text = getPmDate(data[position].createTime)
                runCatching {
                    calorieValueText.text = buildString {
                        append((data[position].caloriesDaily * data[position].servings).toInt())
                        append(" ")
                        append(context.getString(R.string.calories))
                    }
                    proteinText.text = "${(data[position].proteinDaily * data[position].servings).roundToInt()}g"
                    carbsText.text = "${(data[position].carbsDaily * data[position].servings).roundToInt()}g"
                    fatsText.text = "${(data[position].fatsDaily * data[position].servings).roundToInt()}g"

                    val ingredients = Gson().fromJson(
                        data[position].ingredients,
                        InfoIngredientsBean::class.java
                    )
                    val serving = ingredients?.servingTypes?.find {
                        return@find it.id == ingredients.servingTypeId
                    }
                    if(data[position].type==4){
                        if (serving?.metricUnit == "g" || serving?.metricUnit == "G") { //g数
                            calorieValueText.text = buildString {
                                append((data[position].caloriesDaily))
                                append(" ")
                                append(context.getString(R.string.calories))
                            }
                            proteinText.text = "${(data[position].proteinDaily)}g"
                            carbsText.text = "${(data[position].carbsDaily)}g"
                            fatsText.text = "${(data[position].fatsDaily)}g"
                        }else{ //份数
                            calorieValueText.text = buildString {
                                append((data[position].caloriesDaily * data[position].servings).toInt())
                                append(" ")
                                append(context.getString(R.string.calories))
                            }
                            proteinText.text = "${(data[position].proteinDaily * data[position].servings).roundToInt()}g"
                            carbsText.text = "${(data[position].carbsDaily * data[position].servings).roundToInt()}g"
                            fatsText.text = "${(data[position].fatsDaily * data[position].servings).roundToInt()}g"
                        }
                    }else{
                        calorieValueText.text = buildString {
                            append((data[position].caloriesDaily * data[position].servings).toInt())
                            append(" ")
                            append(context.getString(R.string.calories))
                        }
                        proteinText.text = "${(data[position].proteinDaily * data[position].servings).roundToInt()}g"
                        carbsText.text = "${(data[position].carbsDaily * data[position].servings).roundToInt()}g"
                        fatsText.text = "${(data[position].fatsDaily * data[position].servings).roundToInt()}g"
                    }

                }

                when (data[position].showType) {
                    1 -> {
                        emptyView1.stopRotation()
                        emptyView2.stopRotation()
                        emptyView3.stopRotation()
                        emptyView4.stopRotation()
                        finalText.stopSwitching()
                        dataLayout.isVisible = true
                        noneLayout.isVisible = false
                        failLayout.isVisible = false
                    }

                    2 -> { //加载中
                        emptyView1.startAnimation()
                        emptyView2.startAnimation()
                        emptyView3.startAnimation()
                        emptyView4.startAnimation()
                        finalText.startSwitching()
                        dataLayout.isVisible = false
                        noneLayout.isVisible = true
                        failLayout.isVisible = false
                    }

                    3 -> { //失败
                        emptyView1.stopRotation()
                        emptyView2.stopRotation()
                        emptyView3.stopRotation()
                        emptyView4.stopRotation()
                        finalText.stopSwitching()
                        dataLayout.isVisible = false
                        noneLayout.isVisible = false
                        failLayout.isVisible = true
                    }
                }

                contentLayout.setOnClickListener {
                    if (data[position].showType != 1) return@setOnClickListener
                    val currentPosition = holder.adapterPosition
                    if (currentPosition != RecyclerView.NO_POSITION) {
                        onClick.invoke(0, currentPosition, it)
                    }
                }
                tapToText.setOnClickListener {
                    val currentPosition = holder.adapterPosition
                    if (currentPosition != RecyclerView.NO_POSITION) {
                        onClick.invoke(1, currentPosition, it)
                    }
                }
                xImg.setOnClickListener {
                    val currentPosition = holder.adapterPosition
                    if (currentPosition != RecyclerView.NO_POSITION) {
                        onClick.invoke(2, currentPosition, it)
                    }
                }

            }

            is FoodViewHolder -> { // 拍照扫描的食物
                val dataLayout = holder.itemView.findViewById<ConstraintLayout>(R.id.dataLayout)
                val noneLayout = holder.itemView.findViewById<ConstraintLayout>(R.id.noneLayout)
                val failLayout = holder.itemView.findViewById<ConstraintLayout>(R.id.failLayout)

                val nameText = holder.itemView.findViewById<TextView>(R.id.nameText)
                val pmText = holder.itemView.findViewById<TextView>(R.id.pmText)

                val calorieValueText = holder.itemView.findViewById<TextView>(R.id.calorieValueText)
                val proteinText = holder.itemView.findViewById<TextView>(R.id.proteinText)
                val carbsText = holder.itemView.findViewById<TextView>(R.id.carbsText)
                val fatsText = holder.itemView.findViewById<TextView>(R.id.fatsText)
                val runImg = holder.itemView.findViewById<ImageView>(R.id.runImg)
                val loadImg = holder.itemView.findViewById<RotateImageView>(R.id.loadImg)
                val loadView = holder.itemView.findViewById<View>(R.id.loadView)
                val progressText = holder.itemView.findViewById<ProgressTextView>(R.id.progressText)
                val finalText = holder.itemView.findViewById<AutoSwitchTextView>(R.id.finalText)
                val emptyView1 = holder.itemView.findViewById<LoadLinearView>(R.id.emptyView1)
                val emptyView2 = holder.itemView.findViewById<LoadLinearView>(R.id.emptyView2)
                val emptyView3 = holder.itemView.findViewById<LoadLinearView>(R.id.emptyView3)
                val emptyView4 = holder.itemView.findViewById<LoadLinearView>(R.id.emptyView4)



                val tapToText = holder.itemView.findViewById<TextView>(R.id.tapToText)
                val xImg = holder.itemView.findViewById<ImageView>(R.id.xImg)
                val contentLayout =
                    holder.itemView.findViewById<ConstraintLayout>(R.id.contentLayout)

                finalText.apply {
                    setTextList(texts)
                    startSwitching()
                }
                if (data[position].img.isEmpty()) {
                    runImg.isVisible = false
                } else {
                    runImg.isVisible = true
                    Glide.with(context)
                        .load(data[position].img)
                        .into(runImg)
                }
                nameText.text = data[position].foodName
                pmText.text = getPmDate(data[position].createTime)
                runCatching {
                    calorieValueText.text = buildString {
                        append((data[position].caloriesDaily * data[position].servings).toInt())
                        append(" ")
                        append(context.getString(R.string.calories))
                    }
                    proteinText.text = "${(data[position].proteinDaily * data[position].servings).roundToInt()}g"
                    carbsText.text = "${(data[position].carbsDaily * data[position].servings).roundToInt()}g"
                    fatsText.text = "${(data[position].fatsDaily * data[position].servings).roundToInt()}g"
                }

//                data[position].job?.cancel()

                when (data[position].showType) {
                    1 -> {
                        emptyView1.stopRotation()
                        emptyView2.stopRotation()
                        emptyView3.stopRotation()
                        emptyView4.stopRotation()
                        finalText.stopSwitching()
                        dataLayout.isVisible = true
                        noneLayout.isVisible = false
                        failLayout.isVisible = false
                        loadImg.isVisible = false
                        loadView.isVisible = false
                        progressText.isVisible = false
                        loadImg.stopRotate()
                        progressText.startProgressAnimation()
                    }
                    2 -> { //加载中
                        emptyView1.startAnimation()
                        emptyView2.startAnimation()
                        emptyView3.startAnimation()
                        emptyView4.startAnimation()
                        finalText.startSwitching()
                        dataLayout.isVisible = false
                        noneLayout.isVisible = true
                        failLayout.isVisible = false
                        loadImg.isVisible = true
                        loadView.isVisible = true
                        progressText.isVisible = true
                        loadImg.startRotate()
                        progressText.startProgressAnimation()

                    }

                    3 -> { //失败
                        emptyView1.stopRotation()
                        emptyView2.stopRotation()
                        emptyView3.stopRotation()
                        emptyView4.stopRotation()
                        finalText.stopSwitching()
                        dataLayout.isVisible = false
                        noneLayout.isVisible = false
                        failLayout.isVisible = true
                        loadImg.isVisible = false
                        loadView.isVisible = false
                        progressText.isVisible = false
                        loadImg.stopRotate()
                        progressText.startProgressAnimation()

                    }
                }

                contentLayout.setOnClickListener {
                    runCatching {
                        val currentPosition = holder.adapterPosition
                        if (data[currentPosition].showType != 1) return@setOnClickListener
                        if (currentPosition != RecyclerView.NO_POSITION) {
                            onClick.invoke(0, currentPosition, runImg)
                        }
                    }

                }
                tapToText.setOnClickListener {
                    val currentPosition = holder.adapterPosition
                    if (currentPosition != RecyclerView.NO_POSITION) {
                        onClick.invoke(1, currentPosition, it)

                    }
                }
                xImg.setOnClickListener {
                    val currentPosition = holder.adapterPosition
                    if (currentPosition != RecyclerView.NO_POSITION) {
                        onClick.invoke(2, currentPosition, it)
                    }
                }

            }

            is EditViewHolder -> {
            }
        }

    }
}


//override fun getItemCount(): Int {
//    return when (state) {
//        State.NORMAL -> data.size
//        else -> 1 // 非NORMAL状态显示1个Item
//    }
//}

//// 更新状态并刷新界面
//fun updateState(newState: RecentlyState, errorMessage: String? = null) {
//    state = newState
//    errorMessage?.let { errorMsg = it }
//    notifyDataSetChanged()
//}

// 各状态ViewHolder定义
class RunViewHolder(view: View) : RecyclerView.ViewHolder(view)
class WeightViewHolder(view: View) : RecyclerView.ViewHolder(view)

class FoodNameViewHolder(view: View) : RecyclerView.ViewHolder(view)
class FoodViewHolder(view: View) : RecyclerView.ViewHolder(view)
class EditViewHolder(view: View) : RecyclerView.ViewHolder(view)

//    class ErrorViewHolder(view: View) : RecyclerView.ViewHolder(view) {
//        fun bind(message: String) {
//            itemView.findViewById<TextView>(R.id.tvError).text = message
//        }
//    }
//    class NormalViewHolder(view: View) : RecyclerView.ViewHolder(view) {
//        fun bind(text: String) {
//            itemView.findViewById<TextView>(R.id.tvItem).text = text
//        }
//    }
